package com.yenlien.traceyun.plant.service;

import com.yenlien.traceyun.common.utils.RandomUtil;
import com.yenlien.traceyun.common.utils.Tools;
import com.yenlien.traceyun.plant.dao.OrderDao;
import com.yenlien.traceyun.plant.dao.OrderDetailedDao;
import com.yenlien.traceyun.plant.entity.Order;
import com.yenlien.traceyun.plant.entity.OrderDetailed;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by LiuSha on 2020/7/28.
 */
@Service
public class OrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderDetailedDao orderDetailedDao;

    public Page<Order> findByList(final Order order) {
        Pageable pageable = PageRequest.of(order.getPage(), order.getPageSize(), Sort.Direction.DESC, "createtime");
        return orderDao.findAll(new Specification<Order>() {
            private static final long serialVersionUID = 1L;

            @Override
            public Predicate toPredicate(Root<Order> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<String> companyId = root.get("companyId");
                //构造查询条件
                List<Predicate> list = new ArrayList<>();
                List<Predicate> or = new ArrayList<>();
                if (!StringUtils.isEmpty(order.getCompanyId())) {
                    list.add(cb.equal(companyId, order.getCompanyId()));
                }
                if (!StringUtils.isEmpty(order.getState())) {
                    list.add(cb.equal(root.get("state"), order.getState()));
                }
                if (!StringUtils.isEmpty(order.getStart())) {
                    try {
                        list.add(cb.greaterThanOrEqualTo(root.get("createtime"), new SimpleDateFormat("yyyy-MM-dd").parse(order.getStart())));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                if (!StringUtils.isEmpty(order.getEnd())) {
                    try {
                        list.add(cb.lessThanOrEqualTo(root.get("createtime"), new SimpleDateFormat("yyyy-MM-dd").parse(order.getEnd())));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                Predicate[] predicate = new Predicate[list.size()];
                Predicate pre_and = cb.and(list.toArray(predicate));
                return pre_and;
            }
        }, pageable);
    }

    @Transactional
    public void save(Order order) {
        String totalAmount = "0";
        if (order.getOrderDetailedList() != null && order.getOrderDetailedList().size() > 0) {
            for (OrderDetailed orderDetailed : order.getOrderDetailedList()) {
                totalAmount = Tools.addtr(totalAmount, orderDetailed.getTotalPrice());
            }
            order.setTotalAmount(totalAmount);
        }
        order.setOrderCode(Tools.getDateAll() + RandomUtil.randomNum(4));
        if (!StringUtils.isEmpty(order.getPayStatus()) && order.getPayStatus().equals("未付款")) {
            order.setState("1");
        } else {
            order.setState("2");
        }
        order.setCreatetime(new Date());
        orderDao.save(order);
        if (order.getOrderDetailedList() != null && order.getOrderDetailedList().size() > 0) {
            for (OrderDetailed orderDetailed : order.getOrderDetailedList()) {
                orderDetailed.setOrderId(order.getId());
                orderDetailed.setCreatetime(new Date());
                orderDetailedDao.save(orderDetailed);
            }
        }
    }

    public void update(Order order) {
        String totalAmount = "0";
        if (order.getOrderDetailedList() != null && order.getOrderDetailedList().size() > 0) {
            for (OrderDetailed orderDetailed : order.getOrderDetailedList()) {
                totalAmount = Tools.addtr(totalAmount, orderDetailed.getTotalPrice());
            }
            order.setTotalAmount(totalAmount);
        }
        orderDao.save(order);
        if (order.getOrderDetailedList() != null && order.getOrderDetailedList().size() > 0) {
            for (OrderDetailed orderDetailed : order.getOrderDetailedList()) {
                orderDetailed.setOrderId(order.getId());
                orderDetailedDao.save(orderDetailed);
            }
        }
    }

    public Order findById(String id) {
        Order order = orderDao.findById(id);
        order.setOrderDetailedList(orderDetailedDao.findByOrderId(id));
        return order;
    }

    @Transactional
    public void delete(String id) {
        orderDao.deleteById(id);
        List<OrderDetailed> orderDetaileds = orderDetailedDao.findByOrderId(id);
        if (orderDetaileds != null && orderDetaileds.size() > 0) {
            orderDetailedDao.deleteAll(orderDetaileds);
        }
    }
}
